<template>
    <ul class="list">
        <li class="item" v-for="item of letters"
            @click="handleLetterClick"
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
        >
            {{item}}
        </li>
    </ul>
</template>

<script>
    export default {
        name: "alphabet",
        props: {
            cities: Object
        },
        data(){
            return{
                touchLetter: false,
                startY: false
            }
        },
        computed:{
            letters(){
                var arr=[]
                for (var k in this.cities){
                    arr.push(k);
                }
                return arr;
            },
            touchLetterIndex(){
                // 好大一个坑！害得鄙人花了一个多小时！
                // this.touchLetter 原本是用字母赋值的，怎知竟会被 Vue 偷偷转换成了数组？？
                var char=this.touchLetter[0]
                return this.letters.indexOf(char);
            }
        },
        methods: {
            handleLetterClick(e){
                var letter=e.target.innerHTML.replace(/\s*/, '');
                this.$emit('updateLetter', letter)
                console.log('Click:'+this.touchLetter)
            },
            handleTouchStart(e){
                var letter=e.target.innerHTML.replace(/\s*/, '');
                this.touchLetter=letter;
                this.startY=e.touches[0].clientY;
            },
            handleTouchMove(e){
                var h=e.target.offsetHeight;
                var Y=e.touches[0].clientY;
                var index=Math.floor((Y-this.startY)/h)+this.touchLetterIndex;

                // 用不着判断 index 的取值范围！
                this.$emit('updateLetter', this.letters[index])
            },
            handleTouchEnd(e){
                // 本事件多余，可以直接删掉了
                // this.touchLetter=false
            }
        }
    }
</script>

<style scoped lang="stylus">
    @import "~@styles/variables.styl"
    .list
        position: absolute
        width: .4rem
        top: 1.8rem
        right: 0
        bottom: 0
        line-height: $lineHeight*0.48
        display: flex
        flex-direction: column
        justify-content: center
        .item
            text-align: center
            color: $bgColor_head
</style>